package com.gogowan.agroenterprise.storage;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.BoxCode;
import com.gogowan.agroenterprise.model.IntStorageBoxRequest;
import com.gogowan.agroenterprise.model.IntStorageBoxResult;
import com.gogowan.agroenterprise.model.IntStorageReault;
import com.gogowan.agroenterprise.model.IntStorageRequest;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.StoreListResult;
import com.gogowan.agroenterprise.model.StoreModel;
import com.gogowan.agroenterprise.model.StoreRequest;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.StoreSpinnerAdapter;
import com.gogowan.agroenterprise.widget.adapter.XMListViewAdapter;

/**
 * 入库
 * 
 * @author tjh 2017-01-13
 *
 */
public class InStorageActivity extends Activity implements OnClickListener {
	private ProgressDialog progressDialog;
	
	private List<StoreModel> storeList = new ArrayList<StoreModel>();
	private List<StoreModel> hwList = new ArrayList<StoreModel>();
	private List<StoreModel> hwList2 = new ArrayList<StoreModel>();
	private Spinner ckSpinner, hwSpinner;
	private EditText dhEdit;
	private StoreSpinnerAdapter storeSpinnerAdapter;
	private StoreSpinnerAdapter hwSpinnerAdapter;

	private ListView xmListView;
	private XMListViewAdapter xMListViewAdapter;
	private List<BoxCode> boxCodeList = new ArrayList<BoxCode>();

	private long storeId;
	private List<String> codeStringList = new ArrayList<String>();
	private ArrayList<String> resultStringList;

	private Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				storeSpinnerAdapter.notifyDataSetChanged();
				break;
//			case 1:
//				hwSpinnerAdapter.notifyDataSetChanged();
//				hwSpinner.setSelection(0);
//				break;
			case 2:
				xMListViewAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_in_storage);

		initView();
		initValue();
	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		// 仓库
		ckSpinner = (Spinner) findViewById(R.id.in_storage_ckmc_spinner);
		storeSpinnerAdapter = new StoreSpinnerAdapter(this, storeList, ckSpinner);
		ckSpinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						// TODO Auto-generated method stub
						hwList2.clear();
						StoreModel storeModel = new StoreModel();
						storeModel.setStoreID(-1);
						storeModel.setStoreName("请选择货位");
						hwList2.add(storeModel);
						storeId = storeList.get(position).getStoreID();
						for (int i = 0; i < hwList.size(); i++) {
							if (hwList.get(i).getParentCode() == storeId) {
								hwList2.add(hwList.get(i));
							}
						}
						myHandler.sendEmptyMessage(1);
					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						// TODO Auto-generated method stub

					}
				});
		ckSpinner.setAdapter(storeSpinnerAdapter);
//
//		// 货位
//		hwSpinner = (Spinner) findViewById(R.id.in_storage_hw_spinner);
//		hwSpinnerAdapter = new StoreSpinnerAdapter(this, hwList2);
//		hwSpinner
//				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//
//					@Override
//					public void onItemSelected(AdapterView<?> parent,
//							View view, int position, long id) {
//						// TODO Auto-generated method stub
//						if (hwList2.get(position).getStoreID() != -1) {
//							storeId = hwList2.get(position).getStoreID();
//						}
//					}
//
//					@Override
//					public void onNothingSelected(AdapterView<?> parent) {
//						// TODO Auto-generated method stub
//
//					}
//				});
//		hwSpinner.setAdapter(hwSpinnerAdapter);

		xmListView = (ListView) findViewById(R.id.in_storage_xmlist);
		xMListViewAdapter = new XMListViewAdapter(this, boxCodeList);
		xmListView.setAdapter(xMListViewAdapter);

		ImageButton fhBtn = (ImageButton) findViewById(R.id.in_storage_fh_btn);
		fhBtn.setOnClickListener(this);
		dhEdit = (EditText) findViewById(R.id.in_storage_dh_edit);

		ImageView smhqdhBtn = (ImageView) findViewById(R.id.in_storage_smhqdh_btn);
		smhqdhBtn.setOnClickListener(this);
		ImageView smhqckBtn = (ImageView) findViewById(R.id.in_storage_smhqck_btn);
		smhqckBtn.setOnClickListener(this);
//		Button smhqhwBtn = (Button) findViewById(R.id.in_storage_smhqhw_btn);
//		smhqhwBtn.setOnClickListener(this);
		Button smrkxmBtn = (Button) findViewById(R.id.in_storage_smrkxm_btn);
		smrkxmBtn.setOnClickListener(this);
		Button qrrkBtn = (Button) findViewById(R.id.in_storage_qrrk_btn);
		qrrkBtn.setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initValue() {

		progressDialog = ProgressDialog.show(this,
				getString(R.string.alert_title),
				getString(R.string.alert_message), true, false);

		StoreRequest storeRequest = new StoreRequest();
//		storeRequest.setEnterpriseID(loginResultInfo.getEnterpriseinfo()
//				.getEnterpriseid());
//		storeRequest.setDealerID(loginResultInfo.getEnterpriseinfo()
//				.getDealerId());
//		storeRequest.setUserType(loginResultInfo.getEnterpriseinfo()
//				.getUserType());
		storeRequest.setUserID(MyApplication.mSettings.getLong("personid",0));
		storeRequest.setPageIndex(1);
		storeRequest.setType(0);
		storeRequest.setParentCode(0);

		GetStorageListAsyn getStorageListAsyn = new GetStorageListAsyn();
		getStorageListAsyn.execute(storeRequest);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.in_storage_fh_btn:
			// 返回
			this.finish();
			break;
		case R.id.in_storage_smhqdh_btn:
			// 扫码获取单号
			intent = new Intent(Intents.Scan.ACTION);
			this.startActivityForResult(intent, 10);
			break;
		case R.id.in_storage_smhqck_btn:
			// 扫码获取仓库
			intent = new Intent(Intents.Scan.ACTION);
			this.startActivityForResult(intent, 20);
			break;
//		case R.id.in_storage_smhqhw_btn:
//			// 扫码获取货位
//			intent = new Intent(Intents.Scan.ACTION);
//			this.startActivityForResult(intent, 30);
//			break;
		case R.id.in_storage_smrkxm_btn:
			// 扫描入库箱码
			intent = new Intent(Intents.Scan.ACTION);
			intent.putExtra(Intents.Scan.IS_BULT_MODE, true);
			this.startActivityForResult(intent, 40);
			break;
		case R.id.in_storage_qrrk_btn:
			// 确认入库
			if (TextUtils.isEmpty(dhEdit.getText())) {
				Toast.makeText(this, "请输入单号", Toast.LENGTH_LONG).show();
			} else {
				progressDialog = ProgressDialog.show(this,
						getString(R.string.alert_title),
						getString(R.string.alert_message), true, false);

				IntStorageRequest intStorageRequest = new IntStorageRequest();
				intStorageRequest.setStorageId(storeId);
//				intStorageRequest.setEnterpriseId(loginResultInfo
//						.getEnterpriseinfo().getEnterpriseid());
//				intStorageRequest.setUserId(loginResultInfo.getUserinfo()
//						.getPersonid());
				intStorageRequest.setOrder(dhEdit.getText() + "");
//				intStorageRequest.setDealeId(loginResultInfo
//						.getEnterpriseinfo().getDealerId());
				intStorageRequest.setBoxCode(boxCodeList);

				IntStorageAsyn intStorageAsyn = new IntStorageAsyn();
				intStorageAsyn.execute(intStorageRequest);
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			String codeStr;
			switch (requestCode) {
			case 10:
				// 扫码获取单号
				codeStr = data.getStringExtra(Intents.Scan.RESULT);
				dhEdit.setText(codeStr);
				break;
			case 20:
				// 扫码获取仓库
				codeStr = data.getStringExtra(Intents.Scan.RESULT);
				boolean isTrue = true;
				for (int i = 0; i < storeList.size(); i++) {
					if (storeList.get(i).getEwmUrl().equalsIgnoreCase(codeStr)) {
						ckSpinner.setSelection(i);
						isTrue = false;
						break;
					}
				}
				if (isTrue) {
					Toast.makeText(InStorageActivity.this, "请扫描正确的仓库码",
							Toast.LENGTH_LONG).show();
				}
				break;
			case 30:
				// 扫码获取货位
				codeStr = data.getStringExtra(Intents.Scan.RESULT);
				boolean isHW = true;
				for (int i = 0; i < hwList.size(); i++) {
					if (hwList.get(i).getEwmUrl().equalsIgnoreCase(codeStr)) {
						long storid = hwList.get(i).getParentCode();
						hwList2.clear();
						for (int j = 0; j < hwList.size(); j++) {
							if (hwList.get(j).getParentCode() == storid) {
								hwList2.add(hwList.get(j));
							}
						}

						for (int j = 0; j < storeList.size(); j++) {
							if (storeList.get(j).getStoreID() == storid) {
								ckSpinner.setSelection(j);
								break;
							}
						}

						for (int j = 0; j < hwList2.size(); j++) {
							if (hwList2.get(j).getEwmUrl()
									.equalsIgnoreCase(codeStr)) {
								hwSpinner.setSelection(j);
								break;
							}
						}
						isHW = false;
						break;
					}
				}
				if (isHW) {
					Toast.makeText(InStorageActivity.this, "请扫描正确的货位码",
							Toast.LENGTH_LONG).show();
				}
				break;
			case 40:
				// 扫描入库箱码
				resultStringList = data
						.getStringArrayListExtra(Intents.Scan.RESULTLIST);
				if (resultStringList == null || resultStringList.size() == 0) {
					return;
				}
				progressDialog = ProgressDialog.show(this,
						getString(R.string.alert_title),
						getString(R.string.alert_message), true, false);

				IntStorageBoxRequest intStorageBoxRequest = new IntStorageBoxRequest();
//				intStorageBoxRequest.setEnterpriseId(loginResultInfo
//						.getEnterpriseinfo().getEnterpriseid());
				intStorageBoxRequest.setBoxCode(resultStringList);

				IntStorageBoxRequestAsyn intStorageBoxRequestAsyn = new IntStorageBoxRequestAsyn();
				intStorageBoxRequestAsyn.execute(intStorageBoxRequest);
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 获取仓库列表
	 * 
	 * @author tjh
	 *
	 */
	private class GetStorageListAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(InStorageActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(InStorageActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					StoreListResult storeListResult = (StoreListResult) Utils
							.fromJSON(string, StoreListResult.class);
					if (storeListResult.getResult() == 21000) {
						if (storeListResult.getStoreList() != null) {
							storeList.clear();
							hwList.clear();
							for (int i = 0; i < storeListResult.getStoreList()
									.size(); i++) {
								if (storeListResult.getStoreList().get(i)
										.getType() == 1) {
									storeList.add(storeListResult
											.getStoreList().get(i));
								} else {
									hwList.add(storeListResult.getStoreList()
											.get(i));
								}
							}
						}

						myHandler.sendEmptyMessage(0);
					} else {
						Toast.makeText(InStorageActivity.this,
								storeListResult.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			StoreRequest storeRequest = (StoreRequest) params[0];
			String json = Utils.toJSON(storeRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					21000, true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 箱码列表
	 * 
	 * @author tjh
	 *
	 */
	private class IntStorageBoxRequestAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(InStorageActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(InStorageActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					IntStorageBoxResult intStorageBoxResult = (IntStorageBoxResult) Utils
							.fromJSON(string, IntStorageBoxResult.class);
					if (intStorageBoxResult.getResult() == 14001) {
						if (intStorageBoxResult.getBoxInfo() != null) {
							boxCodeList
									.addAll(intStorageBoxResult.getBoxInfo());
							codeStringList.addAll(resultStringList);
							myHandler.sendEmptyMessage(2);
						}
					} else {
						Toast.makeText(InStorageActivity.this,
								intStorageBoxResult.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			IntStorageBoxRequest intStorageBoxRequest = (IntStorageBoxRequest) params[0];
			String json = Utils.toJSON(intStorageBoxRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					18100, true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 入库请求
	 * 
	 * @author tjh
	 *
	 */
	private class IntStorageAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(InStorageActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(InStorageActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					IntStorageReault intStorageReault = (IntStorageReault) Utils
							.fromJSON(string, IntStorageReault.class);
					if (intStorageReault.getResult() == 14006) {
						InStorageActivity.this.finish();
					}
					Toast.makeText(InStorageActivity.this,
							intStorageReault.getResultinfo(), Toast.LENGTH_LONG)
							.show();
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			IntStorageRequest intStorageRequest = (IntStorageRequest) params[0];
			String json = Utils.toJSON(intStorageRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					182000, true, json);
			String ss = Utils.toJSON(message);
			Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		storeList.clear();
		storeList = null;
		hwList.clear();
		hwList = null;
		hwList2.clear();
		hwList2 = null;
		storeSpinnerAdapter = null;
		hwSpinnerAdapter = null;
		xMListViewAdapter = null;
		boxCodeList.clear();
		boxCodeList = null;
	}
}
